import { download } from "/@/utils/download";
import NotifMessage from "/@/utils/message/notification";
import router from "/@/router/index";
import { storageLocal } from "/@/utils/storage";

export const uploadUrl =
  import.meta.env.VITE_BASE_URL + "/snow-admin/common/file/upload";

export const uploadUrlImport =
  import.meta.env.VITE_BASE_URL + "/snow-admin/qtyCheck/importInsContent";

const FileTypes = {
  doc: "application/msword",
  docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  xls: "application/vnd.ms-excel",
  xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  pdf: "application/pdf",
  png: "image/png",
  jpg: "image/jpeg",
  jpeg: "image/jpeg"
};

const xlsxFile = {
  xls: "application/vnd.ms-excel",
  xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
};

export const acceptTypes = Object.values(FileTypes).join(",");
export const acceptXlsxTypes = Object.values(xlsxFile).join(",");

export const uploadHeaders = {
  Authorization: storageLocal.getItem("info")?.accessToken
};

export const handlePreview = file => {
  console.log(file, "file");
  if (file?.response?.code !== 200 || !file?.response?.data) return;
  download(file?.response?.data);
};

export const handleError = err => {
  let myError = err.toString(); //转字符串
  myError = myError.replace("Error: ", ""); // 去掉前面的" Error: "
  myError = JSON.parse(myError); //转对象
  myError?.message && NotifMessage.error(myError?.message);

  if (myError?.body?.code && [401, 403].includes(myError?.body?.code)) {
    myError?.body?.message && NotifMessage.error(myError?.body?.message);
    router.push("/login");
    storageLocal.removeItem("info");
  }
};

export const beforeAvatarUpload = file => {
  // const type = file.type.slice(file.type.lastIndexOf("/") + 1);
  const type = file.name.substring(file.name.lastIndexOf(".") + 1);
  if (!Object.keys(FileTypes).includes(type)) {
    NotifMessage.warning(`请上传${Object.keys(FileTypes).join("、")}等格式!`);
    return false;
  }

  const isLt2M = file.size / 1024 / 1024 < 20;

  if (!isLt2M) {
    NotifMessage.warning(`文件大小不能超过20M!`);
    return false;
  }
};

export const beforeXmlUpload = file => {
  const type = file.name.substring(file.name.lastIndexOf(".") + 1);
  if (!Object.keys(xlsxFile).includes(type)) {
    NotifMessage.warning(`请上传${Object.keys(xlsxFile).join("、")}等格式!`);
    return false;
  }

  const isLt2M = file.size / 1024 / 1024 < 20;

  if (!isLt2M) {
    NotifMessage.warning(`文件大小不能超过20M!`);
    return false;
  }
};

export const onInitFileList = (list: any[]) => {
  if (!list || !list.length || !list[0]?.fileName) return;
  const newFileList = list.map(item => {
    return {
      name: item?.fileName,
      response: {
        data: item,
        code: 200
      }
    };
  });
  return newFileList;
};

export const onFilterFileData = (list: any[]) => {
  if (!list || !list.length) return;
  const newFileData = list.map(item => {
    // if (item.status === "success") {
    return item.response && item.response.data;
    // }
  });
  return newFileData;
};

/**
 * URL方式保存文件到本地
 * @param name 文件名
 * @param data 文件的数据
 */
 function save(name, data) {
  const urlObject: any = window.URL || window.webkitURL;
  const export_blob = new Blob([data]);
  let save_link: HTMLAnchorElement = document.createElement("a");
  save_link.href = urlObject.createObjectURL(export_blob);
  save_link.download = name;
  save_link.click();
  urlObject.revokeObjectURL(save_link.href);
  save_link = null;
}

export function downloadUrlFile(url: string, name: string) {
  const xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);
  xhr.responseType = "blob";
  xhr.onload = () => {
    if (xhr.status == 200) {
      // 获取图片blob数据并保存
      save(name, xhr.response);
    }
  };

  xhr.send();
}
